/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.hisense.settings;

import com.hisense.settings.util.PreferenceUtils;
//import com.google.tv.AVSettings;
//import com.google.tv.avapi.TvMode;
//import com.google.tv.avapi.TvMode.DisplayMode;
//import com.google.tv.settings.util.EventLogger;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.ContentObserver;
import com.android.settings.R;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;

import android.os.ServiceManager;
import android.media.AudioManager;

import com.google.android.tv.provider.TvUriUtils;
import com.hisense.settings.device.PairingDevice;
import com.google.android.tv.mediadevices.Device;
import com.google.android.tv.mediadevices.MediaDevicesIntents;
import com.google.android.tv.mediadevices.IMediaDevicesService;
import com.google.android.tv.mediadevices.MediaDevicesConstants;
import java.util.List;


public class PowerOnReceiver extends BroadcastReceiver {

	private static final String TAG = "PowerOnReceiver";
    public static final String ACTION_LAUNCH_SETTING = "com.google.tv.launcher.HISENSE_POWERON_SETTING";
	//private static final int SOURCE_TV = 1;
	private AudioManager mAudioManager;

	private static final int SOURCE_REMEMBER = 0;
	private static final int SOURCE_TV = 1;
	private static final int SOURCE_COMPOSITE = 2;
	private static final int SOURCE_COMPONENT = 3;
	private static final int SOURCE_HDMI1 = 4;
	private static final int SOURCE_HDMI2 = 5;
	private static final int SOURCE_HDMI3 = 6;
	private static final int SOURCE_HDMI4 = 7;
	private static final int SOURCE_VGA = 8;
	private static String DEVICE_ID = null;

	private static Thread sourceTvSetThread = null;
	
    @Override
    public void onReceive(final Context context, Intent intent) {

    	if (ACTION_LAUNCH_SETTING.equals(intent.getAction())) {
			Log.d(TAG, "LauncherIntent " 
				+ "com.google.tv.launcher.HISENSE_POWERON_SETTING");         		

			//int source = Settings.Secure.getInt(context.getContentResolver(),
            //        "power_on_source_num",-1);
            final int source = Settings.Secure.getInt(context.getContentResolver(),
                    "power_on_source_num",0);

			if(source == SOURCE_TV) {
				if(sourceTvSetThread==null)
				{
					sourceTvSetThread = new Thread() {
						@Override
						public void run() {
//							String str = GetChannelUriFromChannelDBByChannelNumber(context,Settings.Secure.getString(context.getContentResolver(),"power_on_channel_name"));
							String str =Settings.Secure.getString(context.getContentResolver(),"power_on_channel_uri");
							Log.d(TAG, "str" + str);
							if(str != null)
							{
								final Uri channelUri = Uri.parse(str);
								Intent intentchannel = new Intent(Intent.ACTION_VIEW, channelUri);
								intentchannel.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
								PreferenceUtils.setBootIntent(context.getContentResolver(), intentchannel);
								String sourceId = getSourceUrlString(source);
								Log.d(TAG, "LauncherIntent sourceId " 
									+ sourceId);  
								Intent defaultIntent = MediaDevicesIntents.createServiceDefaultDeviceIntent(sourceId);
								Log.d(TAG, "defaultIntent" + intentchannel);
								Log.d(TAG, "defaultIntent" + defaultIntent);
								context.startActivity(intentchannel);
							}
							else
							{
								String sourceId = getSourceUrlString(source);
								Uri dataUri = TvUriUtils.PASSTHROUGH_URI.buildUpon()
					            .appendQueryParameter(
					                    TvUriUtils.DEVICE_ID_QUERY_PARAMETER,
					                    sourceId)
					            .build();
								Intent srcintent = new Intent(Intent.ACTION_VIEW, dataUri);
								srcintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
								PreferenceUtils.setBootIntent(context.getContentResolver(), srcintent);	

								Log.d(TAG, " sourceId " 
									+ sourceId);  
								Intent defaultIntent = MediaDevicesIntents.createServiceDefaultDeviceIntent(sourceId);
								Log.d(TAG, "defaultIntent" + srcintent);
								Log.d(TAG, "defaultIntent" + defaultIntent);
								context.startActivity(srcintent);
							}
						}
					};
					sourceTvSetThread.start();
					Log.d(TAG, "SOURCE_TV: thread null,start");
				}
				else{
					sourceTvSetThread.run();
					Log.d(TAG, "SOURCE_TV: thread not null,run");
				}
				
				/*
				String str = GetChannelUriFromChannelDBByChannelNumber(context,Settings.Secure.getString(context.getContentResolver(),"power_on_channel_name"));
				final Uri channelUri = Uri.parse(str);
				Intent intentchannel = new Intent(Intent.ACTION_VIEW, channelUri);
				PreferenceUtils.setBootIntent(context.getContentResolver(), intentchannel);
				*/
				//Intent srcintent = Pairing.createServiceDefaultDeviceIntent(PairingDevice.TUNER_DEVICE_ID);
				//context.startService(srcintent);			
			}
/*			else if(source != SOURCE_REMEMBER){
			Log.d(TAG, "source change " 
				+ "srcintent.srcintent.srcintent.srcintent.srcintent");  				
				//Intent srcintent = changeSource(source);
				//if(srcintent != null)
				//context.startService(srcintent);
				String sourceId = getSourceUrlString(source);
				
//				Uri dataUri = TvUriUtils.PASSTHROUGH_URI.buildUpon()
//	            .appendQueryParameter(
//	                    TvUriUtils.DEVICE_ID_QUERY_PARAMETER,
//	                    sourceId)
//	            .build();
				Intent srcintent=PreferenceUtils.getBootIntent(context.getContentResolver());
//				Intent srcinten = new Intent(Intent.ACTION_VIEW, dataUri);
//				PreferenceUtils.setBootIntent(context.getContentResolver(), srcinten);

//				Intent defaultIntent = MediaDevicesIntents.createServiceDefaultDeviceIntent(sourceId);
				Log.d(TAG, "srcintent" + srcintent);
//				Log.d(TAG, "defaultIntent" + defaultIntent);
				srcintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
				context.startActivity(srcintent);
			}
*/			//power on sound		
			setPowerVolume(context);   
        }
        
    }
    private void setPowerVolume(Context context) {
		int sound_enable = Settings.Secure.getInt(context.getContentResolver(),
                    "settings_power_sound_enable",0);
		if(sound_enable == 1) {
			int volume = Settings.Secure.getInt(context.getContentResolver(),
						"settings_power_sound_value",30);
			
			mAudioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
			mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume,
							AudioManager.FLAG_PLAY_SOUND);	
		}
	}
	private String GetChannelUriFromChannelDBByChannelNumber(Context context,String channel_number)
	{
		ContentResolver resolver =context.getContentResolver();
		ContentValues values = new ContentValues();
		Uri uri=Uri.parse("content://com.google.android.tv.provider/channel_listing");
		Cursor mcursor=resolver.query(uri, new String[]{"channel_number", "channel_uri"}, null, null,null);
		String channelurl = null;
        try {
			while(mcursor.moveToNext()){
			   //String channel_name = Settings.Secure.getString(getContentResolver(),"power_on_channel_name");
			   String channelName=mcursor.getString(mcursor.getColumnIndexOrThrow("channel_number"));
			   if(channelName == null) continue;
			   if(channelName.equals(channel_number)){			
				   //return mcursor.getString(mcursor.getColumnIndexOrThrow("channel_uri"));
				   channelurl = mcursor.getString(mcursor.getColumnIndexOrThrow("channel_uri"));
				   break;
			   }		   
			}

        } finally {
			if (mcursor != null) { 
				try { 
					mcursor.close(); 
				} 
				catch (Exception e) {
				}
			}
        }
		/*
		while(mcursor.moveToNext()){
		   //String channel_name = Settings.Secure.getString(getContentResolver(),"power_on_channel_name");
		   String channelName=mcursor.getString(mcursor.getColumnIndexOrThrow("channel_number"));
		   if(channelName == null) continue;
		   if(channelName.equals(channel_number)){	   		
			   return mcursor.getString(mcursor.getColumnIndexOrThrow("channel_uri"));		   
		   }		   
		}
		if (mcursor != null) { 
			try { 
				mcursor.close(); 
			} 
			catch (Exception e) {
			}
		}
		*/
		return channelurl;
	}
	public String getSourceUrlString(int source_num) {
		String str = null;
		
		if (source_num == SOURCE_TV) {
			str = PairingDevice.TUNER_DEVICE_ID;
		}
		else if (source_num == SOURCE_COMPOSITE) {
			str = PairingDevice.COMPOSITE_DEVICE_ID;
		}
		else if (source_num == SOURCE_COMPONENT) {
			str = PairingDevice.COMPONENT_DEVICE_ID;
		}
		else if (source_num == SOURCE_HDMI1) {
			str = PairingDevice.HDMI1_DEVICE_ID;
		}		
		else if (source_num == SOURCE_HDMI2) {
			str = PairingDevice.HDMI2_DEVICE_ID;
		}	
		else if (source_num == SOURCE_HDMI3) {
			str = PairingDevice.HDMI3_DEVICE_ID;
		}	
		else if (source_num == SOURCE_HDMI4) {
			str = PairingDevice.HDMI4_DEVICE_ID;
		}	
		else if (source_num == SOURCE_VGA) {
			str = PairingDevice.VGA_DEVICE_ID;
		}	
		return str;

	}	
}

